class Table < ActiveRecord::Base
  has_many :card
  has_many :bet
  has_many :player
  has_many :log
  has_one :current_player, :class_name => 'player'
  has_one :button_player, :class_name => 'player'

  def to_list_json
    a = '{ '
    a<<'"id":'<<self.id.to_s<<','
    a<<'"name":"'<<self.name<<'",'
    a<<'"playersCount":'<<self.maxPlayers.to_s<<','
    a<<'"playersActual":'<<self.player.all.count.to_s
    a<<' }'
    return a
  end

  def state_to_json
    a = "{"
    a<<'"id":'<<self.id<<','
    a<<'"players":['
    self.player.each { |player|
      a<<'"'<<player.login<<'",'
    }
    a.chop if a.last.eql?(',')
    a<<']'
    a<<'"stage":'<<self.stage<<','
    a<<'"bets":'<<'['
    for i in 1..self.stage
      a<<Bet.to_stage_json(i)<<','
    end
    a.chop if a.last.eql?(',')
    a<<'],'
    log = self.log.find_last_by_stage(self.stage-1)
    a<<'"previousTurn":'<<self.log.find_last_by_stage(self.stage-1).to_json<<',' unless log.nil?
    a<<'"currentPlayer":"'<<self.current_player.login<<'",'
    a<<'"buttonPlayer":"'<<self.current_player.login<<'",'
  end
end
